<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of app_controller
 *
 * @author luis
 */

class AppController extends Controller {

    var $components = array('Email', 'MysqlBackup', 'Session');
    var $helpers = array('Session', 'Html');
    var $uses = array('Backup');

    function beforeFilter(){

        parent::beforeFilter();

        $this->_checkBackup();

    }

    function _checkBackup(){

        $difference = 0;

        $lastBackup = $this->Backup->field("Backup.fecha", array(), "Backup.fecha DESC");


        $backupTime = new DateTime($lastBackup);
        $now        = new DateTime();


        $diff = (int) $now->format("U") - (int) $backupTime->format("U");

        $difference = $diff / 60;

        if(!$lastBackup){
            $difference = 6;
        }
        
        if($difference > 5){
            $this->Session->write('backup', '1');
        }
    }

    function _backup(){

        App::import('Core', 'ConnectionManager');
        $dataSource = ConnectionManager::getDataSource('default');
        $host = $dataSource->config['host'];
        $user = $dataSource->config['login'];
        $pass = $dataSource->config['password'];
        $name = $dataSource->config['database'];

        $backup = $this->MysqlBackup->backup_tables($host,$user,$pass,$name);
        
        $hash = md5($backup);
        
        $filename = "backup_".$hash.".sql";

        $fp = fopen("./backup/".$filename, "w");
        fwrite($fp, $backup);
        fclose($fp);

        return $hash;

    }

    function _sendBackupMail($backup){
        $this->Email->delivery = 'smtp';
        //$this->Email->delivery = 'debug';

        $this->Email->smtpOptions = array(
            'port'=>Configure::read('smtp_port'),
            'timeout'=>Configure::read('smtp_timeout'),
            'auth' => true,
            'host' => Configure::read('smtp_host'),
            'username'=>Configure::read('smtp_username'),
            'password'=>Configure::read('smtp_password')
        );


        $this->Email->to = Configure::read('smtp_username')." <".Configure::read('smtp_username').">";
        $this->Email->subject = 'Backup '.date("Y-m-d H:i:s", time());
        $this->Email->from = Configure::read('smtp_username')." <".Configure::read('smtp_username').">";
        $this->Email->layout = 'default';
        $this->Email->template = 'simple_message'; // note no '.ctp'
        //Send as 'html', 'text' or 'both' (default is 'text')
        $this->Email->sendAs = 'text'; // because we like to send pretty mail
        //Set view variables as normal
        $this->set('body', 'Backup enviado el '.date("Y-m-d H:i:s", time()));

        $this->Email->attachments = array(
            "backup.sql" => "./backup/backup_".$backup.".sql"
        );

        //Do not pass any args to send()

        $currentHash = $backup;
        $lastHash = $this->Backup->field("Backup.hash", array(), "Backup.id DESC");
        $this->Session->delete('backup');

        if($currentHash != $lastHash){
            $this->Backup->save(array(
                "Backup" => array(
                    "fecha" => date("Y-m-d H:i:s", time()),
                    "hash"  => $lastHash
                )
            ));

            if($this->Email->send()){
                $id = $this->Backup->field("Backup.id", array(), "Backup.id DESC");
                $this->Backup->save(array(
                    "Backup" => array(
                        "id" => $id,
                        "hash"  => $currentHash
                    )
                ));
            }else{
                echo $this->Email->smtpError;
            }

            echo $this->Email->smtpError;
        }else{
            $this->Backup->save(array(
                "Backup" => array(
                    "fecha" => date("Y-m-d H:i:s", time()),
                    "hash"  => $currentHash
                )
            ));
        }
    }
    
} 
?>
